import {APP_NAME_KEY, BASE_URL, LOCK_ENUM} from "../../constant/index";
import EventBus from "../../utils/eventBus";
import {delay, showValidateTip, toast, getRoomTags} from "../../utils/tool";

const app = getApp()
Page({
    data: {
        showShare: false,
        shareID: '',
        flag: false,
        text: '',
        statusHeight: wx.getSystemInfoSync().statusBarHeight,
        show: false,
        showLock: false,
        roomPop: false,
        bookstore: {},
        // 默认店铺的距离
        firstDis: '',
        // 弹窗是否显示
        popshow: false,
        // 卡片项数据
        firstStore: wx.getStorageSync('firststore') || {}, //置顶门店
        cardData: [], //门店包间的数据
        storeList: [], //门店列表数据
        user: {},
        city: {},
        lat: '',
        lon: '',
        order_id: 0,
        blueYaCode: '',
        stores: [],
        banner: [], //首页轮播图
        // 轮播图相关
        background: [],
        indicatorDots: true,
        bookshow: false,
        storeshow: false,
        // 时间数据
        times: {},
        allTimes: [],
        logoUrl: '',
        //确认的开始时间
        confirmTime: '',
        confirmEndTime: '',
        select_date: '',
        select_start: '',
        select_end: '',
        nums: 0,
        date_arr: [],
        id: '', //门店id
        imgUrl: BASE_URL,
        showCalc: false,
        weekDate: [],
        activeTab: 0,
        timeList: [],
        swiperData: [],
        showLocationPop: false, // 未授权定位弹窗
        isShare: false,
        hasLoad: false,
        tagList: ['有停车位', '免费WIFI', '智慧共享'],
        isEmpty: false,
        shouldUpdate: true,
        isScroll: false,
        timerId: null,
    },
    scrollHandle() {
        if (this.timerId) {
            clearTimeout(this.timerId)
            this.timerId = null
        }
        this.setData({isScroll: true})
        this.timerId = setTimeout(() => {
            this.setData({isScroll: false})
        }, 300)
    },
    getTodayDateStr() {
        const date = new Date()
        const [year, month, day] = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
        return `${year}-${('0' + month).slice(-2)}-${('0' + day).slice(-2)}`
    },

    initTimeList(data) {
        console.log(data, 'data')
        const result = []
        const todayStr = this.getTodayDateStr()
        const todayTimestamp = new Date(todayStr).getTime()
        const oneDay = 1000 * 60 * 60 * 24
        for (const key in data) {
            const target = data[key]
            const {local_time} = target
            const [date] = local_time.split(' ')
            const timestamp = new Date(date).getTime()
            const index = (timestamp - todayTimestamp) / oneDay
            if (result[index]) {
                result[index].push(target)
            } else {
                result[index] = [target]
            }
        }
        console.log(result, 'result@@')
    },

    getWeek(day) {
        const weekEnum = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        return weekEnum[day] || ''
    },
    formatDate(timestamp, isToday, index) {
        const date = new Date(timestamp)
        const [month, day] = [date.getMonth() + 1, date.getDate()]
        const desc = isToday ? '今天' : this.getWeek(date.getDay())
        return {
            label: `${('0' + month).slice(-2)}.${('0' + day).slice(-2)}`,
            desc,
            index,
            value: timestamp,
        }
    },
    initWeekDate() {
        const date = new Date()
        const oneDay = 1000 * 60 * 60 * 24
        const result = []
        for (let i = 0; i < 5; i++) {
            result.push(this.formatDate(date.getTime() + (i * oneDay), i === 0, i))
        }
        this.setData({
            weekDate: result
        })
        console.log(result, 'result')
    },
    closeLayer() {
        this.setData({
            bookshow: false
        })
    },
    toGroupBuying() {
        wx.navigateTo({
            url: '/pages/validate-ticket/validate-ticket'
        })
    },
    closeCalc() {
        this.setData({
            showCalc: false
        })
    },
    initLogoUrl() {
        app.ajax({
            url: '/api/banner/indexlogo',
            success: resp => {
                if (resp.code !== 1) return
                this.setData({
                    logoUrl: BASE_URL + resp.data
                })
            }
        })
    },
    bookcancel() {
        this.setData({
            bookshow: false
        })
    },
    toUrl(ev) {
        const {path} = ev.currentTarget.dataset
        if (!!path) {
            wx.navigateTo({
                url: path
            })
        }
    },
    // 公告
    getVoice() {
        // app.ajax({
        //     url: '/api/index/advert',
        //     data: {},
        //     success: res => {
        //         if (res.code == 1) {
        //             this.setData({
        //                 advert: res.data
        //             })
        //         }
        //     }
        // })
    },
    openHand() {
        this.setData({
            showLock: true
        })
    },
    // 打开地图
    openMap: function () {
        let arr = this.data.firstStore.lat.split(",")
        const lat = parseFloat(arr[1]),
            lon = parseFloat(arr[0]),
            firstStore = this.data.firstStore;
        if (!lat || !lon) {
            return false;
        }
        wx.openLocation({
            latitude: lon,
            longitude: lat,
            scale: 15,
            name: firstStore.name,
            address: firstStore.address,
            success: function (res) {
            },
            fail: function (res) {
            }
        })
    },
    clickSwiper() {
        return this.joinCompany()
    },
    joinCompany() {
        wx.navigateTo({
            url: '/pages/join/join'
        })
    },
    // 开包间房门
    opensmall() {
        wx.switchTab({
            // url:"/pages/my-reserve/my-reserve",
            url: '/pages/my-order/my-order',
        })
    },
    // 开大门
    openDoor() {
        const {firstStore: {id}} = this.data
        app.ajax({
            url: '/api/frontdoor/openfrontdoor',
            data: {
                store_id: id
            },
            success: res => {
                toast({title: res.msg})
            }
        })
    },
    // 获取门店
    getfirst() {
        let location = wx.getStorageSync('location')
        app.ajax({
            url: '/api/room/storebyplace',
            data: {
                lon: location.lon,
                lat: location.lat
            },
            success: res => {
                if (!res.data.length) return toast({title: '没有获取到门店'})
                const [activeStore] = res.data
                if (!activeStore) return toast({title: '没有获取到门店'})
                this.setData({firstStore: activeStore})
                app.setFirst(activeStore)
                this.findRooms(activeStore.id)
                this.data.hasLoad = true
            }
        })
    },
    // 预订选择时间
    stopBubb: function () {
        return false
    },
    getSelectedTimes: function () {
        app.ajax({
            url: '/api/index/getAllTImes',
            data: {
                id: this.data.id,
                date: this.data.select_date
            },
            success: res => {
                if (res.code == 1) {
                    // this.setData({
                    //     allTimes: res.data,
                    // })
                    this.data.allTimes = res.data
                    // this.initTimeList(res.data)
                    this.getTimes()
                }
            }
        }, 1);
    },
    getTimes: function () {
        var datenow = this.data.select_date;
        datenow = datenow.replace(/-/g, "/")
        var start = new Date(datenow + ' 00:00:00').getTime().toString()
        start = start.substr(0, 10)
        start = parseInt(start)
        var end = start + 60 * 60 * 24 - 1
        // var end = start + (60 * 60 * 24) * 2
        var times = {}
        const {allTimes} = this.data
        const _end = end + 60 * 60 * 24 - 1
        for (let key in allTimes) {
            if (key >= start && key <= end) {
                const target = allTimes[key]
                target.isNext = false
                times[key] = target
            }
            // 找到第二天的
            if (key >= end && key <= _end) {
                const target = allTimes[key]
                target.isNext = true
                times[key] = target
            }
        }
        this.setData({
            times: times
        })
    },

    selectTime: function (e) {
        var times = this.data.allTimes,
            index = parseInt(e.currentTarget.dataset.index),
            time = e.currentTarget.dataset.time,
            select_start = this.data.select_start,
            select_end = this.data.select_end;
        if (times[index].disabled) {
            return false;
        }
        if (select_start !== '' && select_end !== '') {
            for (let i in times) {
                times[i].select = false;
            }
            times[index].select = true;
            this.setData({
                select_start: index,
                select_end: '',
                nums: 0,
                allTimes: times
            })
        } else if (select_start !== '') {
            if (select_start == index) {
                times[index].select = false;
                this.setData({
                    select_start: '',
                    allTimes: times
                });
                return false;
            } else if (index > select_start) {
                select_end = index;
            } else {
                select_end = select_start;
                select_start = index;
            }
            var error = false,
                nums = 0;
            for (let i in times) {
                times[i].select = false;
                if (i >= select_start && i <= select_end) {
                    if (times[i].disabled) {
                        error = true;
                    }
                    times[i].select = true;
                    nums += 1;
                }
            }
            if (nums > 0) nums -= 1;
            if (error) {
                wx.showToast({
                    title: '存在不可选项',
                    icon: 'none'
                });
                return false;
            }
            this.setData({
                select_start: select_start,
                select_end: select_end,
                allTimes: times,
                nums: nums
            })
        } else {
            times[index].select = true;
            this.setData({
                allTimes: times,
                select_start: index
            })
        }
        this.getTimes()
    },
    // 切换门店
    changestore() {
        wx.navigateTo({
            url: '/pages/changestore/changestore',
        })
    },
    slideClick(ev) {
        const {type} = ev.currentTarget.dataset
        if (type === 'open') return wx.switchTab({url: '/pages/my-order/my-order'})
        if (type === 'service') return this.callPhone()
        return wx.navigateTo({url: '/pages/history_order/history_order'})
    },
    // 查询全部店铺
    getStore() {
        const {lat, lon} = this.data
        let params = {}
        if (!!lat && !!lon) {
            params.lat = lat
            params.lon = lon
        }
        app.ajax({
            url: "/api/room/storelist",
            data: params,
            success: res => {
                this.setData({
                    storeList: res.data
                })
            }
        })
    },
    // 时间组件
    // 点击tab切换
    swichNav: function (e) {
        var date = e.currentTarget.dataset.date;
        if (this.data.select_date == date) {
            return false;
        } else {
            this.setData({
                select_date: date
            });
            this.getTimes();
        }
    },
    getDate: function (now) {
        let date = new Date(now),
            y = date.getFullYear(),
            m = date.getMonth() + 1,
            w = date.getDay(),
            d = date.getDate(),
            weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        m = ('0' + m).slice(-2);
        d = ('0' + d).slice(-2);
        return {
            week: weeks[w],
            date: y + '/' + m + '/' + d,
            name: m + '.' + d
        };
    },
    tochongzhi() {
        this.setData({
            bookshow: false,
        })
        wx.navigateTo({
            url: '/pages/group-buying/group-buying',
        })
    },
    confirm_book: function () {
        const {bookstore} = this.data;
        // var data1 = this.data.allTimes;
        // let times = encodeURIComponent(JSON.stringify(data1))
        let roomData = encodeURIComponent(JSON.stringify(bookstore))
        const c = this.data.nums
        const flag = c < 6
        if (flag) return toast({title: '定时间三小时起'})
        const id_str = `&id=${this.data.id}`
        wx.navigateTo({
            url: '/pages/book/book?newdata=' + roomData + '&selectstart=' + this.data.select_start +
                '&selectend=' + this.data.select_end + '&nums=' + this.data.nums + '&type=bookTime' + id_str
        })
        this.setData({
            bookshow: false
        })
    },
    accountPopupClose(ev) {
        const {detail} = ev
        this.toConfirmPage(detail)
    },
    toConfirmPage(payload) {
        if (!payload) return
        wx.navigateTo({
            url: `/pages/book/book?info=${JSON.stringify(payload)}`
        })
    },
    chooseRoomHandle(e) {
        // const hasMobile = app.checkHasMobile()
        const hasMobile = true
        if (!hasMobile) return wx.showModal({
            title: '提示',
            content: '您的账号未绑定手机号,请前往授权绑定!',
            success: () => wx.navigateTo({url: '/pages/login/login'})
        })
        const {detail: payload} = e
        // const popup = this.selectComponent('#accountPopup')
        // if (!!popup) return popup.open(true, payload)
        this.toConfirmPage(payload)
    },
    // 美团验券
    meituan: function () {
        return showValidateTip()
        wx.navigateTo({
            url: '/pages/group-buying/group-buying?type=' + 2
        })
    },
    formatTime(timestamp) {
        const date = new Date(timestamp)
        const [hour, minutes] = [date.getHours(), date.getMinutes()]
        return `${('0' + hour).slice(-2)}:${('0' + minutes).slice(-2)}`
    },
    patchRoomList(data) {
        // function getRoomTags(tagStr) {
        //     if (!tagStr) return []
        //     let prefixStr = ''
        //     if (tagStr.includes('，')) {
        //         prefixStr = '，'
        //     } else if (tagStr.includes(',')) {
        //         prefixStr = ','
        //     } else {
        //         prefixStr = ' '
        //     }
        //     return tagStr.split(prefixStr).filter(Boolean)
        // }

        const textEnum = {1: '空闲中', 3: '待保洁', 4: '保洁中'}
        return data.map(item => {
            item.image = BASE_URL + item.image
            const {status, end_time, room_tags} = item
            item.room_tags = getRoomTags(room_tags)
            const _status = Number(status)
            const showTime = _status === 2 && !isNaN(end_time)
            let status_text = ''
            if (showTime) {
                const endTime = this.formatTime(end_time * 1000)
                status_text = `截止时间 ${endTime}`
                item.endTime = endTime
            } else {
                status_text = textEnum[_status]
            }
            item.statusText = status_text
            item.status = _status
            return item
        })
    },
    // 查询 门 店的包间
    findRooms(e, loading = false) {
        if (loading) wx.showLoading({title: '正在获取', mask: true})
        app.ajax({
            url: "/api/room/selcetroombystore",
            data: {storeid: e},
            success: async res => {
                if (loading) await delay(420)
                const {code, msg} = res
                if (!res.data) res.data = []
                if (code !== 1) toast({title: msg})
                // app.setRoomList(data)
                const result = this.patchRoomList(res.data)
                this.setData({
                    cardData: result,
                    isEmpty: !(result.length)
                })
                if (loading) wx.hideLoading()
            }
        })
    },
    // 获取首页轮播图
    getBanner() {
        app.ajax({
            url: '/api/banner/bannerlist',
            data: {
                type: 1
            },
            success: res => {
                const {data} = res
                if (!data) return
                this.setData({
                    banner: data
                })
            }
        })
    },
    // 开大门
    async openDoorBig() {
        let self = this
        self.setData({
            popshow: true
        })
    },

    history_order: function () {
        wx.navigateTo({
            url: '/pages/history_order/history_order'
        })
    },
    contactWifi() {
        const {id: store_id} = this.data.firstStore
        app.ajax({
            url: '/api/room/storewifi',
            data: {store_id},
            success: res => {
                const {code, data, msg} = res
                if (code !== 1) return toast({title: msg})
                if (!data.length) return toast({title: '当前门店无wifi'})
                const [target] = data
                const {wifi_account, wifi_password} = target
                const refTarget = this.selectComponent('#wifiPop')
                if (!refTarget) return
                refTarget.open(wifi_account, wifi_password)
            }
        })
    },
    callPhone() {
        wx.showModal({
            title: '提示',
            content: '您确定要拨打客服电话吗?',
            confirmText: '拨打',
            cancelText: '取消',
            success: ev => {
                if (ev.cancel) return
                wx.makePhoneCall({phoneNumber: this.data.firstStore.mobile,})
            }
        })
    },
    join: function () {
        wx.navigateTo({
            url: '/pages/my_order/my_order'
        })
    },

    initText() {
        return
        app.ajax({
            url: "/api/content/indexshuoming",
            success: resp => {
                const {data} = resp
                this.setData({
                    text: data,
                    show: true,
                });
            }
        })
    },
    openShare() {
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
    },
    calcHandler() {
        this.setData({
            showCalc: true
        })
    },
    onShareAppMessage() {
        return {
            title: app.globalData.appName,
            path: '/pages/index/index',
        }
    },
    checkIsShare(options) {
        const {id: currentUserId} = this.data.user
        if (!options || !options.hasOwnProperty('type')) {
            setTimeout(() => {
                this.initText()
            }, 1000)
            return false
        }
        const {id} = options
        if (id * 1 === currentUserId) {
            setTimeout(() => {
                this.initText()
            }, 1000);
            return false
        }
        this.setData({
            shareID: id,
            showShare: true,
        })
        return true
    },
    shareConfirm() {
        this.setData({
            showShare: false,
        })
        this.initText()
    },
    initSelectTime() {
        const date_arr = [];
        for (let i = 0; i < 5; i++) {
            let now = new Date().getTime() + i * 86400000;
            date_arr.push(this.getDate(now));
        }
        let start_date = this.getDate(Date.now() + 86400000 * 5),
            end_date = this.getDate(Date.now() + 86400000 * 7);
        this.setData({
            date_arr: date_arr,
            date_start: start_date.date,
            date_end: end_date.date,
            select_date: date_arr[0].date
        });
    },
    onLoad: function (options) {
        app.getUserInfo().then(async resp => {
            if (resp.code === 1) {
                this.data.user = resp.data
            }
            this.data.isShare = this.checkIsShare(options)
            this.initLogoUrl()
            this.getSite();
            this.initSelectTime()
            this.getLocation()
        })
        EventBus.$on('change_store_success', this.changeStoreSuccess, this)
    },
    getSite: function () {
        app.ajax({
            url: '/api/index/getSite',
            success: res => {
                if (res.code === 1) {
                    const site = res.data;
                    wx.setStorageSync(APP_NAME_KEY, site.name)
                    wx.setStorageSync('tel', site.tel);
                    wx.setStorageSync('instructions', site.instructions);
                    wx.setStorageSync('about', site.about);
                    wx.setStorageSync('disclaimer', site.disclaimer);
                    wx.setStorageSync('explain', site.explain);
                }
            }
        })
    },

    changeStoreSuccess(store) {
        if (!store) return
        this.setData({firstStore: store})
    },
    getLocation: function () {
        const {firstStore} = this.data
        if (firstStore.hasOwnProperty('name')) {
            this.findRooms(firstStore.id)
            this.data.hasLoad = true
            return
        }
        wx.authorize({
            scope: 'scope.userLocation',
            success: () => {
                this.getUserLocation(false)
            },
            fail: () => {
                this.setData({
                    showLocationPop: true,
                })
            }
        })
        // return new Promise(resolve => {
        //     wx.getLocation({
        //         success: res => {
        //             app.setLocationSetting(1)
        //             this.setData({
        //                 lat: res.latitude,
        //                 lon: res.longitude,
        //             });
        //             wx.setStorageSync('location', {
        //                 lat: res.latitude,
        //                 lon: res.longitude
        //             });
        //             this.getCity()
        //             this.getfirst()
        //             resolve(true)
        //         },
        //         fail: async () => {
        //             const flag = await app.checkLocationSetting()
        //             console.log(flag, 'checkLocationSetting')
        //             if (!flag) {
        //                 resolve(false)
        //                 return toast({title: '获取定位权限失败', time: 2000})
        //             }
        //             const resp = await this.getLocation()
        //             resolve(resp)
        //         }
        //     })
        //
        // })
    },
    getCity: function () {
        app.ajax({
            url: '/api/index/getCity',
            data: {
                lat: this.data.lat,
                lon: this.data.lon
            },
            success: res => {
                if (res.code === 1) {
                    const city = res.data;
                    wx.setStorageSync('city', city);
                    this.setData({
                        city: city
                    });
                }
            }
        })
    },
    closeLockPop() {
        this.setData({
            showLock: false
        })
    },
    openLockHandler(ev) {
        const {detail} = ev
        this.closeLockPop()
        if (detail === LOCK_ENUM.gate) {
            this.openDoor()
            return
        }
        if (detail === LOCK_ENUM.guard) {
            this.opensmall()
        }
    },

    onShow: async function () {
        const {changeStore} = app.globalData
        // console.log(changeStore, 'changeStore')
        if (changeStore) {
            this.findRooms(changeStore.id, true)
            app.globalData.changeStore = null
        } else {
            const {firstStore} = this.data
            if (this.data.hasLoad && this.data.shouldUpdate) {
                this.findRooms(firstStore.id)
            }
        }
        // const city = wx.getStorageSync('city');
        // if (city && city.id !== this.data.city.id) {
        //     this.setData({city});
        // }
        this.getBanner();
        // 查询门店列表
        // this.getStore();
        // this.getVoice()
    },

    getNewOrder: function () {
        app.ajax({
            url: '/api/user/newOrder',
            success: res => {
                if (res.code == 1) {
                    this.setData({
                        order_id: res.data
                    })
                }
            }
        })
    },
    getUserLocation(flag) {
        wx.getLocation({
            type: 'gcj02',
            success: res => {
                console.log(res, 'location')
                this.data.lat = res.latitude.toString()
                this.data.lon = res.longitude.toString()
                wx.setStorageSync('location', {
                    lat: res.latitude,
                    lon: res.longitude
                });
                this.getfirst()
            },
            fail: () => {
                // toast({title: '获取地址失败'})
                this.getfirst()
            }
        })
    },
    onSetting() {
        this.setData({
            showLocationPop: false,
        })
        this.getUserLocation(false)
    },
    onClose() {
        this.setData({
            show: false,
        })
    },
    onUnload() {
        EventBus.$off('change_store_success', this.changeStoreSuccess)
    },
})
